﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;
using Gollie.Mail;

namespace Gollie.Ajax
{
	public class UpdateUser : AjaxResult
	{
		public UpdateUser() : base(null) { }

		public UpdateUser(AjaxArg arg)
			: base(arg)
		{
		}

		protected override void Init(AjaxArg ajaxArg)
		{
			UpdateUserArg arg = (UpdateUserArg)ajaxArg;

			logger.Info("UserId {0} changing profile...", arg.tokenUser);

			try
			{
				UserInfo ui = Database.Queries.GetUser(Convert.ToInt32(arg.tokenUser), true);
				if (ui == null)
					throw new Exception("Gebruiker niet gevonden.");

				string initials = string.IsNullOrEmpty(arg.initials) ? ui.Voorletters : UserInfo.ValidateInitials(arg.initials.Trim());
				string infix = string.IsNullOrEmpty(arg.infix) ? ui.Tussenvoegsel : arg.infix.Trim();
				string sex = arg.sex;
				string lastname = string.IsNullOrEmpty(arg.lastname) ? ui.Achternaam : arg.lastname.Trim();
				string city = string.IsNullOrEmpty(arg.city) ? ui.Woonplaats : arg.city.Trim();
				string username = ui.Gebruikersnaam;
				string newWW = string.IsNullOrEmpty(arg.newww) ? "" : arg.newww;
				string newWWRepeat = string.IsNullOrEmpty(arg.newwwrepeat) ? "" : arg.newwwrepeat;
				string newPin = string.IsNullOrEmpty(arg.pin) ? "" : arg.pin;
				string newPinRepeat = string.IsNullOrEmpty(arg.pinrepeat) ? "" : arg.pinrepeat;

				string email = string.IsNullOrEmpty(arg.email) ? ui.Email : arg.email.Trim();
				string mobile = string.IsNullOrEmpty(arg.mobile) ? ui.Telefoon : arg.mobile.Trim().Replace("-", "").Replace(" ", "");
				string birthdate = string.IsNullOrEmpty(arg.birthdate) ? ui.Geboortedatum.ToString("dd-MM-yyy") : arg.birthdate.Trim();

				string ww = arg.ww;
				UserInfo.ValidateWW(ww);

				UserInfo.ValidateWW(newWW, true);
				if (newWW != newWWRepeat)
					throw new ArgumentException("Wachtwoord en Wachtwoord nogmaals komen niet overeen");

				UserInfo.ValidateEmail(email);

				mobile = UserInfo.ValidateTelePhone(mobile, ui.Role == Role.Customer);

				UserInfo.ValidatePin(newPin, true);
				if (newPin != newPinRepeat)
					throw new ArgumentException("Pincode en Pincode nogmaals komen niet overeen");

				DateTime bdate = UserInfo.ValidateBirthdate(birthdate);

				/* Validation success! */
				string wwHash = Hash.GetHash(ww);
				string newWWHash = newWW.Length > 0 ? Hash.GetHash(newWW) : "";
				string newPinHash = newPin.Length > 0 ? Hash.GetHash(newPin) : "";

				int rows = Database.Queries.UpdateUser(username, wwHash, email, initials, infix, lastname, (sex == "1"), city, bdate, mobile, newWWHash, newPinHash);
				if (rows == 1)
				{
					//refresh session object.
					HttpContext.Current.Session["userinfo"] = Database.Queries.GetUser(username, true);

					logger.Info("Profile changed for user {0}", username);
				}
				else
				{
					logger.Warn("UpdateUser returned no rows");
					throw new Exception("Foutief wachtwoord");
				}
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Info("Change profile failed: {0}", this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Info("Change profile failed: {0}", this.ErrorMessage);
			}
		}
	}
}